package com.gnerv.rabbitmq.manage.service;

import com.gnerv.rabbitmq.manage.mapper.ServerMapper;
import com.gnerv.rabbitmq.manage.model.entity.Server;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Repository;
import org.springframework.util.ObjectUtils;

import static com.gnerv.rabbitmq.manage.cache.ExecSessionPoolCache.SESSION;

@Repository
public class ExecSessionService {

    private static final JSch JSCH = new JSch();

    @Resource
    private ServerMapper serverMapper;

    public Session getSession(String ukId) {
        Session session = SESSION.getIfPresent(ukId);
        if (ObjectUtils.isEmpty(session)) {
            Server server = serverMapper.selectByUkId(ukId);
            try {
                session = JSCH.getSession(server.getUsername(), server.getHost(), server.getPort());
                session.setPassword(server.getPassword());
                session.setConfig("StrictHostKeyChecking", "no");
                session.setTimeout(3000);
                session.connect();
            } catch (JSchException e) {
                throw new RuntimeException(e);
            }
            SESSION.put(ukId, session);
        }
        return SESSION.getIfPresent(ukId);
    }

}
